<template>
  <div
    class="product-card"
    :class="{ 'inactive-product': !isProductActive }"
    @click="navigateToDetail"
  >
    <!-- 商品图片 -->
    <div class="product-image-container">
      <img
        :src="productImage || '/placeholder-product.jpg'"
        :alt="productName"
        class="product-image"
        @error="handleImageError"
      />
      <!-- 折扣标签 -->
      <div v-if="discountRate && isProductActive && shouldShowDiscount(discountRate)" class="discount-tag">{{ discountRate }}折</div>
      <!-- 新品标签 -->
      <div v-if="isNewProduct && isProductActive" class="new-tag">新品</div>
      <!-- 状态标签 -->
      <div v-if="!isProductActive" class="status-tag inactive">已下架</div>
      <!-- 收藏按钮 -->
      <el-button
        circle
        class="wishlist-btn"
        :class="{ active: isWishlisted }"
        @click.stop="toggleWishlist"
        :disabled="!isProductActive"
      >
        <el-icon>
          <StarFilled v-if="isWishlisted" />
          <Star v-else />
        </el-icon>
      </el-button>
    </div>

    <!-- 商品信息 -->
    <div class="product-info">
      <!-- 品牌名称 -->
      <p class="brand-name" v-if="brandName">{{ brandName }}</p>

      <!-- 商品名称 -->
      <h3 class="product-name" :title="productName">{{ productName }}</h3>

      <!-- 价格信息 -->
      <div class="price-section">
        <span class="current-price">￥{{ currentPrice?.toFixed(2) }}</span>
        <span v-if="originalPrice && originalPrice > currentPrice" class="original-price"
          >￥{{ originalPrice?.toFixed(2) }}</span
        >
      </div>

      <!-- 销量和评价 -->
      <div class="stats-section">
        <!-- <span class="sales">已售 {{ salesVolume || 0 }} 件</span> -->
        <span class="rating" v-if="rating">
          <el-icon class="star-icon">
            <Star />
          </el-icon>
          {{ rating.toFixed(1) }}
        </span>
      </div>

      <!-- 库存状态 -->
      <div class="stock-status" v-if="stock && stock <= 10">
        <span class="low-stock">库存紧张: {{ stock }} 件</span>
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button
          type="primary"
          size="small"
          :disabled="stock === 0 || !isProductActive"
          @click.stop="handleAddToCart"
        >
          <el-icon>
            <ShoppingCart />
          </el-icon>
          {{ !isProductActive ? '已下架' : '加入购物车' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star, StarFilled, ShoppingCart } from '@element-plus/icons-vue'
import type { Product, Shoes, ProductVO } from '@/types/product'
import { useAuthStore } from '@/stores/auth'
import { useAuthModalStore } from '@/stores/authModal'
import { shouldShowDiscount } from '@/utils/discountUtils'

// 支持两种类型的商品数据
interface Props {
  product: Product | Shoes | ProductVO
}

interface Emits {
  (e: 'add-to-cart', product: Product | Shoes | ProductVO): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const router = useRouter()
const authStore = useAuthStore()
const authModal = useAuthModalStore()

// 类型判断辅助函数
const isShoes = (product: Product | Shoes | ProductVO): product is Shoes => {
  return 'shoeId' in product && 'status' in product
}

const isProductVO = (product: Product | Shoes | ProductVO): product is ProductVO => {
  return 'shoeId' in product && !('status' in product)
}

// 统一的计算属性，处理三种类型的属性映射
const productId = computed(() => {
  if (isShoes(props.product) || isProductVO(props.product)) {
    return props.product.shoeId
  }
  return props.product.id
})

const productName = computed(() => {
  return props.product.name
})

const productImage = computed(() => {
  if (isShoes(props.product) || isProductVO(props.product)) {
    return props.product.productImageUrl
  }
  return props.product.mainImage || (props.product.images && props.product.images[0])
})

const currentPrice = computed(() => {
  if (isShoes(props.product) || isProductVO(props.product)) {
    return props.product.discountPrice || props.product.price
  }
  return props.product.price
})

const originalPrice = computed(() => {
  if (isShoes(props.product) || isProductVO(props.product)) {
    return props.product.discountPrice ? props.product.price : undefined
  }
  return props.product.originalPrice
})

// const salesVolume = computed(() => {
//   if (isShoes(props.product) || isProductVO(props.product)) {
//     return props.product.salesVolume
//   }
//   return props.product.sales
// })

const stock = computed(() => {
  if (isShoes(props.product) || isProductVO(props.product)) {
    return undefined
  }
  return props.product.stock
})

const rating = computed(() => {
  if (isShoes(props.product) || isProductVO(props.product)) {
    return undefined
  }
  return props.product.rating
})

const brandName = computed(() => {
  if (isProductVO(props.product)) {
    return props.product.brand?.brand_name
  }
  if (isShoes(props.product)) {
    // Shoes类型没有brand对象，只有brandId
    return undefined
  }
  return props.product.brandName
})

const discountRate = computed(() => {
  if (
    (isShoes(props.product) || isProductVO(props.product)) &&
    props.product.discountPrice &&
    props.product.price
  ) {
    return Math.round((props.product.discountPrice / props.product.price) * 10)
  }
  if (
    !isShoes(props.product) &&
    !isProductVO(props.product) &&
    props.product.originalPrice &&
    props.product.price
  ) {
    return Math.round((props.product.price / props.product.originalPrice) * 10)
  }
  return undefined
})

const productStatus = computed(() => {
  if (isShoes(props.product)) {
    return props.product.status
  }
  if (!isShoes(props.product) && !isProductVO(props.product)) {
    return props.product.status === 'active' ? '1' : '0'
  }
  return '1' // ProductVO 默认为上架状态
})

const isProductActive = computed(() => {
  return productStatus.value === '1' || productStatus.value === 'active'
})

// 计算属性
const isNewProduct = computed(() => {
  const dateField = isShoes(props.product) ? props.product.launchDate : 
                   isProductVO(props.product) ? undefined : props.product.createTime
  if (!dateField) return false
  const createdDate = new Date(dateField)
  const now = new Date()
  const daysDiff = (now.getTime() - createdDate.getTime()) / (1000 * 60 * 60 * 24)
  return daysDiff <= 7
})

const isWishlisted = computed(() => {
  // 这里应该从用户收藏列表中判断
  return false
})

// 方法
const navigateToDetail = () => {
  router.push(`/product/${productId.value}`)
}

const handleAddToCart = () => {
  if (!isProductActive.value) {
    ElMessage.warning('商品已下架，无法购买')
    return
  }
  if (stock.value === 0) {
    ElMessage.warning('商品已售罄')
    return
  }
  emit('add-to-cart', props.product)
}

const toggleWishlist = () => {
  if (!authStore.isLoggedIn) {
    authModal.openLogin('/user/wishlist', '登录后可使用收藏功能')
    return
  }
  // 这里应该调用添加到收藏夹的API
  if (isWishlisted.value) {
    ElMessage.success('已取消收藏')
  } else {
    ElMessage.success('已加入收藏')
  }
}

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/placeholder-product.jpg'
}
</script>

<style scoped lang="scss">
.product-card {
  background: white;
  border-radius: 8px;
  
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);

    .actions {
      opacity: 1;
    }
  }

  &.inactive-product {
    opacity: 0.7;

    .product-image {
      filter: grayscale(50%);
    }

    &:hover {
      transform: none;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .product-name,
    .current-price {
      color: #999;
    }
  }

  .product-image-container {
    position: relative;
    width: 100%;
    height: 200px;
    

    .product-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .discount-tag,
    .new-tag {
      position: absolute;
      top: 10px;
      left: 10px;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      color: white;
    }

    .discount-tag {
      background: #ff4d4f;
    }

    .new-tag {
      background: #52c41a;
    }

    .status-tag {
      position: absolute;
      top: 10px;
      left: 10px;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      color: white;

      &.inactive {
        background: #999;
      }
    }

    .wishlist-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      border: none;

      &:hover {
        background: rgba(0, 0, 0, 0.7);
      }

      &.active {
        background: #ff4d4f;
        color: white;
      }
    }
  }

  .product-info {
    padding: 15px;

    .brand-name {
      margin: 0 0 5px 0;
      font-size: 12px;
      color: #666;
      text-transform: uppercase;
    }

    .product-name {
      margin: 0 0 10px 0;
      font-size: 14px;
      font-weight: 500;
      color: #333;
      line-height: 1.4;
      height: 40px;
      
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .price-section {
      margin-bottom: 10px;

      .current-price {
        font-size: 18px;
        font-weight: bold;
        color: #ff4d4f;
        margin-right: 8px;
      }

      .original-price {
        font-size: 14px;
        color: #999;
        text-decoration: line-through;
      }
    }

    .stats-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      font-size: 12px;
      color: #666;

      .rating {
        display: flex;
        align-items: center;
        gap: 2px;

        .star-icon {
          color: #faad14;
          font-size: 12px;
        }
      }
    }

    .stock-status {
      margin-bottom: 10px;

      .low-stock {
        font-size: 12px;
        color: #ff4d4f;
        font-weight: bold;
      }
    }

    .actions {
      opacity: 0;
      transition: opacity 0.3s ease;

      .el-button {
        width: 100%;
        height: 32px;
        font-size: 12px;

        &:disabled {
          opacity: 0.5;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .product-card {
    .product-image-container {
      height: 150px;
    }

    .product-info {
      padding: 10px;

      .product-name {
        font-size: 13px;
        height: 36px;
      }

      .price-section {
        .current-price {
          font-size: 16px;
        }

        .original-price {
          font-size: 12px;
        }
      }

      .actions {
        opacity: 1;
      }
    }
  }
}

/* 小屏幕手机优化 */
@media (max-width: 480px) {
  .product-card {
    .product-image-container {
      height: 120px;
      
      .wishlist-btn {
        width: 32px;
        height: 32px;
        font-size: 14px;
      }
    }
    
    .product-info {
      padding: 8px;
      
      .product-name {
        font-size: 12px;
        height: 32px;
        line-height: 16px;
      }
      
      .brand-name {
        font-size: 11px;
        margin-bottom: 4px;
      }
      
      .price-section {
        margin-bottom: 8px;
        
        .current-price {
          font-size: 14px;
        }
        
        .original-price {
          font-size: 11px;
        }
      }
      
      .stats-section {
        margin-bottom: 8px;
        font-size: 11px;
      }
      
      .stock-status {
        margin-bottom: 8px;
        
        .low-stock {
          font-size: 11px;
        }
      }
      
      .actions {
        .el-button {
          height: 36px;
          font-size: 12px;
        }
      }
    }
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .product-card {
    .actions {
      opacity: 1; /* 触摸设备始终显示按钮 */
    }
    
    .wishlist-btn {
      min-width: 44px;
      min-height: 44px;
    }
    
    .actions .el-button {
      min-height: 44px;
    }
  }
}
</style>
